package com.ice.work.study.design.pattern.factory;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.util.ReflectUtil;
import com.ice.work.study.design.pattern.factory.annotation.ProductHandler;
import com.ice.work.study.design.pattern.factory.enums.ProductType;
import com.sun.scenario.effect.impl.prism.PrDrawable;
import org.apache.commons.collections.MapUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description product 工厂类
 * @Author DELL
 * @Create 2019-11-25
 * @Since 1.0.0
 */
public class ProductFactory {

    private final static String PACKAGE_NAME = "com.ice.work.study.design.pattern.factory.impl";
    private static final ProductFactory factory = new ProductFactory();
    private final Map<String, Product> productMap = new ConcurrentHashMap(3);

    private ProductFactory() {
        ClassScanner.scanPackageByAnnotation(PACKAGE_NAME, ProductHandler.class).forEach(clazz -> {
            ProductType handlerTypeEnum = clazz.getAnnotation(ProductHandler.class).value();
            productMap.put(handlerTypeEnum.value(), ReflectUtil.newInstance(clazz.getName()));
        });
    }

    public static ProductFactory getInstance() {
        return factory;
    }


    public Product getProduct(String name) {
        Assert.notBlank(name, "name is null");
        Product product = productMap.get(name);
        return product;
    }
}
